import Vue from 'vue'
// 需要配置nginx 映射
const WS_URL = "ws://"+window.location.host+"/websocket";
const state = {
  msg: '',
  ws: {}
}
let RETRY_TIMES = 3
const WAIT_TIME = 3000
let instanceWs = {}
let connectFlag = false

const mutations = {
  RECEIVE_MSG: (state, msg) => {
    state.msg = msg
  },
  SET_WS: (state, ws) => {
    state.ws = ws
  }
}

const actions = {
  receiveMsg ({commit}, msg) {
    commit('RECEIVE_MSG', msg)
  },

  initWebsocket ({dispatch, commit}) {
    if ('WebSocket' in window) {
      if(!connectFlag) {
        instanceWs = new WebSocket(WS_URL)
        connectFlag = true
        instanceWs.onopen = function () {
          // eslint-disable-next-line no-magic-numbers
          RETRY_TIMES = 3
          instanceWs.send(JSON.stringify({code: 'heart_beat'}))
          console.log('websocket已连接...')
        }
        instanceWs.onclose = function () {
          // websocket 关闭
          connectFlag = false
          console.log('websocket连接已关闭...')
          if (RETRY_TIMES-- > 0) {
            setTimeout(() => {
              dispatch('initWebsocket')
            }, WAIT_TIME)
          }
        }
        instanceWs.onerror = function (e) {
          // websocket 异常
          connectFlag = false
          console.log('websocket连接异常: e' + JSON.stringify(e))
          if (RETRY_TIMES-- > 0) {
            setTimeout(() => {
              dispatch('initWebsocket')
            }, WAIT_TIME)
          }
        }
        instanceWs.onmessage = function (res) {
          if (res) {
            let data = JSON.parse(res.data);
            if (data.code !== 'heart_beat') {
              dispatch('receiveMsg',data);
            } else {
              setTimeout(() => {
                instanceWs.send(JSON.stringify({code: 'heart_beat'}))
              }, WAIT_TIME)
            }
          }
        }
        commit('SET_WS', instanceWs)
      }
    } else {
      // 浏览器不支持 WebSocket
      console.log('您的浏览器不支持 WebSocket!')
    }
  }
}



export default {
  namespaced: true,
  state,
  mutations,
  actions
}
